package com.shelpe.services.sinbad.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.shelpe.services.sinbad.dao.KeywordMapper;
import com.shelpe.services.sinbad.model.CampaignidAndKeywordids;
import com.shelpe.services.sinbad.model.Keyword;
import com.shelpe.services.sinbad.model.KeywordExample;
import com.shelpe.services.sinbad.model.KeywordExample.Criteria;
import com.shelpe.services.sinbad.service.KeywordService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class KeywordServiceImpl implements KeywordService{
	
	@Autowired
	private KeywordMapper keywordMapper;
	
	@Override
	public List<Keyword> getKeywords(Long userId) {
		KeywordExample example = new KeywordExample();
		example.setUserId(userId);
		return keywordMapper.selectByExample(example);
	}

	@Override
	public int save(Keyword keyword, Long userId) {
		keyword.setUserId(userId);
		if(keyword.getOrder()==null){
			keyword.setOrder((short)0);
		}
		if(keyword.getRankScore()==null){
			keyword.setRankScore((short)0);
		}
		return keywordMapper.insertSelective(keyword);
	}

	@Override
	public int update(Keyword keyword, Long userId) {
		keyword.setUserId(userId);
		return keywordMapper.updateByPrimaryKeySelective(keyword);
	}

	private List<Long> toLongList(String params){
		List<Long> values = new ArrayList<Long>();
		for(String param : params.split(",")){
			values.add(Long.valueOf(param.trim()));
		}
		return values;
	}
	
	@Override
	public List<Keyword> getKeywords(Long userId, String adgroupId, String campaignId) {
		log.info(" userId:{}, campaignId:{}, adgroupId:{}", userId, campaignId, adgroupId);
		KeywordExample example = new KeywordExample();
		example.setUserId(userId);
		
		Criteria criteria = example.createCriteria();
		if(adgroupId!=null){
			criteria.andAdgroupIdIn(toLongList(adgroupId));
		}
		if(campaignId!=null){
			criteria.andCampaignIdIn(toLongList(campaignId));
		}
		List<Keyword> ret = keywordMapper.selectByExample(example);
		if(log.isInfoEnabled()){
			log.info("keywords result:{}", JSON.toJSONString(ret));
		}
		return ret;
	}

	@Override
	public int delete(Long userId, String keywordIds) {
		KeywordExample example = new KeywordExample();
		example.setUserId(userId);
		example.createCriteria().andKeywordIdIn(toLongList(keywordIds));
		return keywordMapper.deleteByExample(example);
	}

	@Override
	public List<CampaignidAndKeywordids> getCampaignidAndKeywordids(Long userId, String keywordIds) {
		KeywordExample example = new KeywordExample();
		example.setUserId(userId);
		example.createCriteria().andKeywordIdIn(toLongList(keywordIds));
		return keywordMapper.selectCampaignidAndKeywordidsByExample(example);
	}
	
}
